package com.example.admin.controller.web.common;

import cn.hutool.core.io.FastByteArrayOutputStream;
import com.example.common.util.KaptChaCodeUtil;
import com.example.common.util.RedisUtil;
import com.google.code.kaptcha.Producer;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author chenjf
 * @Date 2022/8/25
 * @Description 验证码
 */
@RestController
@RequestMapping("/captcha")
public class KaptchaCodeController {

    @Autowired
    RedisUtil redisUtil;


    /* 验证码生成 */
    @GetMapping
    public String kaptChaCode(HttpSession session,String uuid) {
        Producer kaptcha = KaptChaCodeUtil.kaptcha();
        //1.生成验证码code
        String text = kaptcha.createText();
        System.out.println("text = " + text);
        //2.将验证码保存至 session作用域中
        session.setAttribute(uuid, text);
        //设置有效时间为5分钟
//        redisUtil.set("kaptcha:" + text, text, 300);
        //3.生成验证码图片
        BufferedImage image = kaptcha.createImage(text);
        //4.写入内存
        FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //3.生成 base64
        //前缀，一般前端添加
        String base64String = Base64.encodeBase64String(fos.toByteArray());
        return "data:image/png;base64," + base64String;
//        return Base64.encodeBase64String(fos.toByteArray());
    }
}
